package com.zhaoyang.servlet;

import com.lizhou.exception.FileFormatException;
import com.lizhou.exception.NullFileException;
import com.lizhou.exception.ProtocolException;
import com.lizhou.exception.SizeException;
import com.lizhou.fileload.FileUpload;
import com.zhaoyang.dao.StudentDao;
import com.zhaoyang.dao.TeacherDao;
import com.zhaoyang.model.Student;
import com.zhaoyang.model.Teacher;
import org.apache.commons.fileupload.FileUploadException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author 赵扬
 * @time 2020/4/28 12:58
 */
@WebServlet("/photoServlet")
public class PhotoServlet extends HttpServlet {
    private static final long serialVersionUID = 1314L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = request.getParameter("method");

        if ("getPhoto".equals(method)) {
            getPhoto(request, response);
        } else if ("SetPhoto".equals(method)) {
            uploadPhoto(request, response);
        }
    }


    private void uploadPhoto(HttpServletRequest request, HttpServletResponse response) {
        //图片上传
        int sid = request.getParameter("sid") == null ? 0 : Integer.parseInt(request.getParameter("sid"));
        int tid = request.getParameter("tid") == null ? 0 : Integer.parseInt(request.getParameter("tid"));
        FileUpload fileUpload = new FileUpload(request);

        fileUpload.setFileFormat("jpg");
        fileUpload.setFileFormat("png");
        fileUpload.setFileFormat("jpeg");
        fileUpload.setFileFormat("gif");
        fileUpload.setFileSize(2048);

        response.setCharacterEncoding("UTF-8");
        try {
            InputStream uploadInputStream = fileUpload.getUploadInputStream();
            // 学生修改头像
            if (sid != 0) {
                Student student = new Student();
                student.setId(sid);
                student.setPhoto(uploadInputStream);

                StudentDao studentDao = new StudentDao();
                if (studentDao.setStudentAvatar(student)) {
                    response.getWriter().write("<div id='message'>上传成功！</div>");
                } else {
                    response.getWriter().write("<div id='message'>上传失败！</div>");
                }
            }
            // 老师修改头像
            if (tid != 0) {
                Teacher teacher = new Teacher();
                teacher.setId(tid);
                teacher.setPhoto(uploadInputStream);
                TeacherDao teacherDao = new TeacherDao();

                if (teacherDao.setTeacherPhoto(teacher)) {
                    response.getWriter().write("<div id='message'>上传成功！</div>");
                } else {
                    response.getWriter().write("<div id='message'>上传失败！</div>");
                }
            }

        } catch (ProtocolException e) {
            try {
                response.getWriter().write("<div id='message'>上传协议错误！</div>");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } catch (NullFileException e) {
            try {
                response.getWriter().write("<div id='message'>上传的文件为空!</div>");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } catch (SizeException e) {
            try {
                response.getWriter().write("<div id='message'>上传文件大小不能超过" + fileUpload.getFileSize() + "！</div>");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } catch (FileFormatException e) {
            try {
                response.getWriter().write("<div id='message'>上传文件格式不正确，请上传 " + fileUpload.getFileFormat() + " 格式的文件！</div>");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } catch (IOException e) {
            try {
                response.getWriter().write("<div id='message'>读取文件出错！</div>");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } catch (FileUploadException e) {
            try {
                response.getWriter().write("<div id='message'>上传文件失败！</div>");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
    }

    private void getPhoto(HttpServletRequest request, HttpServletResponse response) {

        int sid = request.getParameter("sid") == null ?
                0 : Integer.parseInt(request.getParameter("sid"));

        int tid = request.getParameter("tid") == null ?
                0 : Integer.parseInt(request.getParameter("tid"));

        if (sid != 0) {
            //学生
            StudentDao studentDao = new StudentDao();
            Student student = studentDao.getStudent(sid);

            if (student != null) {
                InputStream photo = student.getPhoto();

                if (photo != null) {
                    try {
                        byte[] b = new byte[photo.available()];
                        photo.read(b);
                        response.getOutputStream().write(b, 0, b.length);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return;
                }
            }
        } else if (tid != 0) {
            //教师
            TeacherDao teacherDao = new TeacherDao();
            Teacher teacher = teacherDao.getTeacher(tid);
            if (teacher != null) {
                InputStream photo = teacher.getPhoto();
                if (photo != null) {
                    try {
                        byte[] b = new byte[photo.available()];
                        photo.read(b);
                        response.getOutputStream().write(b, 0, b.length);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return;
                }
            }
        }

        String path = request.getSession().getServletContext().getRealPath("");
        File file = new File(path + "\\imgs\\stu.jpg");
        try {
            FileInputStream fis = new FileInputStream(file);
            byte[] b = new byte[fis.available()];
            fis.read(b);
            response.getOutputStream().write(b, 0, b.length);
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
